package com.whacos.modules.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.whacos.common.annotations.Log;
import com.whacos.common.controller.BaseController;
import com.whacos.common.enums.Constant;
import com.whacos.common.enums.DelFlagEnum;
import com.whacos.common.utils.BeanUtils;
import com.whacos.common.utils.ObjectUtils;
import com.whacos.common.utils.StringUtils;
import com.whacos.common.vo.ResponseVO;
import com.whacos.modules.system.entity.File;
import com.whacos.modules.system.service.FileService;
import com.whacos.modules.system.vo.FileVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author xiongdun
 * @description SysFileController
 * @since 2018/11/17 17:11
 */
@Controller
@RequestMapping("/sys/file")
@Slf4j
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;

    // @Log("跳转文件信息列表")
    @GetMapping()
    @RequiresPermissions("sys:file:file")
    public String file() {
        return "sys/file/file";
    }

    // @Log("查询文件信息列表")
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("sys:file:file")
    public IPage<FileVO> list(FileVO fileVO) {
        IPage<FileVO> sysFileVOPage = new Page<>();
        try {
            // 请求参数
            // 查询分页信息
            IPage<File> sysFilePage = fileService.page(new Page<>(fileVO.getPageNum(), fileVO.getPageSize()),
                    Wrappers.lambdaQuery(new File())
                            .eq(StringUtils.isNotEmpty(fileVO.getName()), File::getFileName, fileVO.getName())
                            .eq(ObjectUtils.isNotEmpty(fileVO.getType()), File::getType, fileVO.getType())
                            .orderByDesc(File::getCreatedDate));

            // 转换被封装新的返回对象VO
            BeanUtils.copyPage(sysFilePage, sysFileVOPage);
        } catch (Exception e) {
            log.error("查询文件列表异常，异常原因：" + e.getMessage(), e);
        }
        return sysFileVOPage;
    }

    // @Log("跳转新增文件信息页面")
    @GetMapping("/add")
    @RequiresPermissions("sys:file:add")
    public String add() {
        return "sys/file/add";
    }

    // @Log("跳转修改文件信息页面")
    @GetMapping("/edit")
    @RequiresPermissions("sys:file:update")
    public String edit(@RequestParam(value = "id") Long id, Model model) {
        File file = fileService.getById(id);
        model.addAttribute("file", file);
        return "sys/file/edit";
    }

    // @Log("获取指定文件信息")
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:file:info")
    public ResponseVO info(@PathVariable("id") Long id) {
        File file = fileService.getById(id);
        return ResponseVO.success().put("sysFile", file);
    }

    @Log("保存指定文件信息")
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("sys:file:add")
    public ResponseVO save(FileVO fileVO) {
        try {
            File file = new File();
            BeanUtils.copyProperties(fileVO, file);

            // 保存数据
            file.createdData(this.getUserId());
            if (fileService.save(file)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("保存文件异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("修改文件信息")
    @ResponseBody
    @PostMapping("/update")
    @RequiresPermissions("sys:file:update")
    public ResponseVO update(FileVO fileVO) {
        try {
            File file = new File();
            BeanUtils.copyProperties(fileVO, file);

            if (fileService.updateById(file)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("修改文件异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error();
        }
        return ResponseVO.success();
    }

    @Log("删除文件信息")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("sys:file:remove")
    public ResponseVO remove(@RequestParam(value = "id") Long id) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            File file = new File();
            file.setId(id);
            file.setDelFlag(DelFlagEnum.DELETE.getValue());
            if (fileService.updateById(file)) {
                int result = fileService.deleteFile(file.getFileName());
                if (result > 0) {
                    return ResponseVO.error("数据库记录删除成功，文件删除失败");
                }
                return ResponseVO.success();
            } else {
                return ResponseVO.error();
            }
        } catch (Exception e) {
            return ResponseVO.error();
        }
    }

    @Log("批量删除文件信息")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("sys:file:batchRemove")
    public ResponseVO batchRemove(@RequestParam("ids[]") List<Long> ids) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (fileService.removeByIds(ids)) {
                return ResponseVO.success();
            }
        } catch (Exception e) {
            log.error("批量删除文件异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(e.getMessage());
        }
        return ResponseVO.success();
    }

    @Log("上传文件")
    @ResponseBody
    @PostMapping("/upload")
    public ResponseVO upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (Constant.DEMO_ACCOUNT.equals(this.getUsername())) {
            return ResponseVO.error(ResponseVO.ERROR_CODE, Constant.DEMO_DESCRIPTION);
        }
        try {
            if (ObjectUtils.isEmpty(file) || file.getSize() <= 0) {
                return ResponseVO.error("上传文件不能为空！");
            }

            FileVO fileVO = fileService.uploadFile(this.getUserId(), file);
            if (ObjectUtils.isNotEmpty(fileVO)) {
                return ResponseVO.success().put("fileName", fileVO.getUrl());
            }
        } catch (Exception e) {
            log.error("上传文件异常，异常原因：" + e.getMessage(), e);
            return ResponseVO.error(e.getMessage());
        }
        return ResponseVO.success();
    }
}
